package com.cgly.medical.security;

import com.alibaba.fastjson.JSON;
import com.cgly.medical.domain.Account;
import com.cgly.medical.entity.AccountModel;
import com.cgly.medical.mapper.AccountMapper;
import com.cgly.medical.util.MyJWT;
import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: CGLY
 * @description:
 * @author: chen di
 * @create: 2022-08-29 01:44
 */

@Component
public class TokenVerifyFilter extends OncePerRequestFilter {


    @Resource
    AccountMapper accountMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("X-Token");
        System.out.println(header);

//        if("null".equals(header))
//            chain.doFilter(request,response);
        if(header!=null){
            //2、解析出userId
            Claims claims = null;
            try {
                claims = MyJWT.parseJWT(header);

            } catch (Exception e) {
                e.printStackTrace();
                //token超时或者非法
                return;
            }
            System.out.println("解密后：" + claims.getSubject());
            Gson gson = new Gson();
            Map map = new HashMap();
            map = gson.fromJson(claims.getSubject(), map.getClass());
            String username = (String) map.get("username");
            Account account = accountMapper.securityLogin(username);
            //4、如果能返回用户信息，存入SecurityContextHolder
            UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(account, null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        chain.doFilter(request,response); //放行
    }
}